package com.hxzy.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.hxzy.common.util.WaimaiThreadLocal;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Desc mybatis-plus实体类重复的字段进行数据填充的增强(spring aop)
 * @Author: admin
 * @Date: 2023/07/05/14:39
 */
@Component
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {

    /**
     * 调用mybatisplus  save()方法
     * @param metaObject  真实的对象（实体对象）
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        //后台用户
        if(WaimaiThreadLocal.getCurrent()!=null) {
            this.strictInsertFill(metaObject, "createBy", String.class, WaimaiThreadLocal.getName());
        }
        //手机端用户
        if(WaimaiThreadLocal.mobileLoginThreadLocal.get()!=null){
            this.strictInsertFill(metaObject, "createBy", String.class, WaimaiThreadLocal.mobileLoginThreadLocal.get().getUserName());
        }
    }

    /**
     * 调用mybatisplus  updateById()方法
     * @param metaObject 真实的对象（实体对象）
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
        //后台用户
        if(WaimaiThreadLocal.getCurrent()!=null) {
            this.strictInsertFill(metaObject, "updateBy", String.class, WaimaiThreadLocal.getName());
        }
        //手机端用户
        if(WaimaiThreadLocal.mobileLoginThreadLocal.get()!=null){
            this.strictInsertFill(metaObject, "createBy", String.class, WaimaiThreadLocal.mobileLoginThreadLocal.get().getUserName());
        }
    }
}
